#!/usr/bin/python
import cPickle



def create_or_load_data_from_cache_file (cache_file_name, data_create_function, 
                                        data_name, use_binary_cache = 1):
    """
    loads data from cache_file_name if exists
        otherwise calls data_create_function() and caches that result
    """
    #
    #   load data from cache file 
    #
    if cache_file_name and os.path.exists(cache_file_name):
        status_log.info("Loading %s data from \n[%s]" % (data_name, cache_file_name))
        cache_file = open(cache_file_name, 'rb')
        data = cPickle.load(cache_file)
        cache_file.close()
        return data
    else:
        data = data_create_function()
    
        #
        #   save to cache 
        #
        if cache_file_name:
            status_log.info("Caching %s data to \n[%s]" %
                                (data_name, cache_file_name))
            cache_file = open(cache_file_name, 'wb')
            cPickle.dump(data, cache_file, use_binary_cache)
            cache_file.close()
    
    return data

